package com.example.sqlitedemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class foodDaoImpl implements foodDao {
    private SQLiteDatabase sqLiteDatabase;
    public MyDBOpenHelper helper;

    public foodDaoImpl(Context context) {
        helper = new MyDBOpenHelper(context);
        sqLiteDatabase = helper.getReadableDatabase();
    }

    @Override
    public List<Food> findAll() {

        List<Food> foodList = new ArrayList<>();
        Cursor cursor=sqLiteDatabase.query("Food", null, null, null, null, null, null);
        while (cursor.moveToNext()){
            Food food = new Food();
            food.setFoodname(cursor.getString(cursor.getColumnIndex("foodname")));
            food.setFoodprice(Double.parseDouble(cursor.getString(cursor.getColumnIndex("foodprice"))));
            food.setCount(Integer.parseInt(cursor.getString(cursor.getColumnIndex("count"))));
            foodList.add(food);
        }
        return foodList;
    }

    @Override
    public List<Food> findFoodByName(String foodName) {
        List foodList = new ArrayList();
        Cursor cursor=sqLiteDatabase.query("Food", null, "where foodname=?", new String[]{foodName}, null, null, null);
        while (cursor.moveToNext()){
            Food food = new Food();
            food.setFoodname(cursor.getString(cursor.getColumnIndex("foodname")));
            food.setFoodprice(Double.parseDouble(cursor.getString(cursor.getColumnIndex("foodprice"))));
            food.setCount(Integer.parseInt(cursor.getString(cursor.getColumnIndex("count"))));
            foodList.add(food);
        }
        return foodList;
    }

    @Override
    public long insert(Food food) {
        ContentValues cv=new ContentValues();
        cv.put("foodname",food.getFoodname());
        cv.put("foodprice",food.getFoodprice());
        cv.put("count",food.getCount());
        sqLiteDatabase.insert("Food",null,cv);
        return 0;
    }

    @Override
    public int delete(String foodName) {
        sqLiteDatabase.delete("Food","where foodname=?",new String[]{foodName});
        return 0;
    }

    @Override
    public int updateFoodPrice(String foodName) {
        ContentValues cv=new ContentValues();
        Food food = new Food();
        cv.put("foodname",food.getFoodname());
        cv.put("foodprice",food.getFoodprice());
        cv.put("count",food.getCount());
        sqLiteDatabase.update("Food",cv,"where foodname=?",new String[]{foodName});
        return 0;
    }
}
